import 'dart:io';

import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:encrypt/encrypt.dart';
import 'package:encrypt/encrypt_io.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sousuoapp/common/auth.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:sousuoapp/https/login_controller.dart';
import 'package:toastification/toastification.dart';
import 'package:sousuoapp/models/user.dart';
import 'package:get_storage/get_storage.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormBuilderState>();
  bool isRemberMe = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var customBorder = OutlineInputBorder(
        borderRadius: BorderRadius.circular(24),
        borderSide: const BorderSide(style: BorderStyle.none));
    final auth = Provider.of<Auth>(context);

    var userName = GetStorage().read('username');
    var psd = GetStorage().read('password');

    void loginFuc() async {
      EasyLoading.show(
        status: '登录中...',
        maskType: EasyLoadingMaskType.black,
      );
      _formKey.currentState?.saveAndValidate();
      if (_formKey.currentState!.isValid) {
        var publicData = await LoginController().getPublicKey();
        RSAKeyParser parser = RSAKeyParser();
        RSAPublicKey publiKey =
            parser.parse(publicData['data']['public']) as RSAPublicKey;
        final encrypter = Encrypter(RSA(publicKey: publiKey));

        var sentData = <String, dynamic>{};
        sentData['username'] =
            encrypter.encrypt(_formKey.currentState?.value['username']).base64;
        sentData['password'] =
            encrypter.encrypt(_formKey.currentState?.value['password']).base64;
        sentData['private_key_id'] = publicData['data']['private_key_id'];
        var data = await LoginController().loginIn(sentData);
        EasyLoading.dismiss();
        if (data['code'] == '1000') {
          User loginData = User.fromJson(data['data']);
          auth.login(loginData.token_key);
          GetStorage()
              .write('username', _formKey.currentState?.value['username']);
          GetStorage()
              .write('password', _formKey.currentState?.value['password']);
          GetStorage().write('h_real_name', '${loginData.h_real_name}');
          GetStorage().write('h_user_info', '${loginData.h_user_info}');
          context.replace('/');
        } else {
          EasyLoading.showToast(data['msg']);
        }

        // Validate and save the form values
      } else {
        _formKey.currentState?.saveAndValidate();
      }
    }

    const colorizeColors = [
      Colors.yellow,
      Colors.blue,
      Colors.yellow,
      Colors.white,
    ];

    const colorizeTextStyle = TextStyle(
      fontSize: 30.0,
      fontFamily: 'Horizon',
    );
    return FlutterEasyLoading(
        child: Scaffold(
            resizeToAvoidBottomInset: false,
            body: Stack(children: [
              Center(
                  child: Container(
                      decoration: const BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('assets/images/background.png'),
                            fit: BoxFit.fill),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const SizedBox(
                            height: 240,
                          ),
                          Container(
                              padding: const EdgeInsets.all(10),
                              color: Colors.transparent,
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10),
                                child: Material(
                                  color: Colors.transparent,
                                  child: FormBuilder(
                                    key: _formKey,
                                    child: Column(
                                      children: [
                                        const SizedBox(
                                          height: 40,
                                        ),
                                        FormBuilderTextField(
                                          name: 'username',
                                          initialValue: userName ?? '',
                                          decoration: InputDecoration(
                                              labelText: '请输入账户',
                                              border: customBorder,
                                              enabledBorder: customBorder,
                                              focusedBorder: customBorder,
                                              focusedErrorBorder: customBorder,
                                              errorBorder: customBorder,
                                              filled: true,
                                              fillColor:
                                                  const Color(0xffF6F6F8),
                                              focusColor:
                                                  const Color(0xffF6F6F8),
                                              hoverColor:
                                                  const Color(0xffF6F6F8),
                                              floatingLabelStyle:
                                                  const TextStyle(
                                                      fontSize: 24,
                                                      color: Colors.black87),
                                              hintStyle: const TextStyle(
                                                  fontSize: 15,
                                                  color: Color(0xffAEAEAE)),
                                              contentPadding:
                                                  const EdgeInsets.symmetric(
                                                      vertical: 12,
                                                      horizontal: 20)),
                                          validator:
                                              FormBuilderValidators.compose([
                                            FormBuilderValidators.required(),
                                          ]),
                                        ),
                                        const SizedBox(height: 40),
                                        FormBuilderTextField(
                                          name: 'password',
                                          initialValue: psd ?? '',
                                          decoration: InputDecoration(
                                              labelText: '密码',
                                              border: customBorder,
                                              enabledBorder: customBorder,
                                              focusedBorder: customBorder,
                                              focusedErrorBorder: customBorder,
                                              errorBorder: customBorder,
                                              filled: true,
                                              fillColor:
                                                  const Color(0xffF6F6F8),
                                              focusColor:
                                                  const Color(0xffF6F6F8),
                                              hoverColor:
                                                  const Color(0xffF6F6F8),
                                              floatingLabelStyle:
                                                  const TextStyle(
                                                      fontSize: 24,
                                                      color: Colors.black87),
                                              hintStyle: const TextStyle(
                                                  fontSize: 15,
                                                  color: Color(0xffAEAEAE)),
                                              contentPadding:
                                                  const EdgeInsets.symmetric(
                                                      vertical: 12,
                                                      horizontal: 20)),
                                          obscureText: true,
                                          validator:
                                              FormBuilderValidators.compose([
                                            FormBuilderValidators.required(),
                                          ]),
                                        ),
                                        const SizedBox(
                                          height: 40,
                                        ),
                                        MaterialButton(
                                          elevation: 24.0,
                                          color: const Color.fromARGB(
                                              255, 21, 211, 50),
                                          textColor: Colors.white,
                                          minWidth: 360.0,
                                          height: 50,
                                          shape: RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.circular(25.0)),
                                          onPressed: loginFuc,
                                          child: const Text('登录'),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              )),
                        ],
                      ))),
              Positioned(
                  top: 160,
                  left: 80,
                  child: Center(
                      child: SizedBox(
                    width: 250.0,
                    child: AnimatedTextKit(
                      animatedTexts: [
                        ColorizeAnimatedText(
                          '重影视觉运营平台',
                          textStyle: colorizeTextStyle,
                          colors: colorizeColors,
                        ),
                      ],
                      repeatForever: true,
                      isRepeatingAnimation: true,
                      onTap: () {
                        print("Tap Event");
                      },
                    ),
                  ))),
            ])));
  }
}
